package cn.edu.zzuli.web.dao;

import java.util.List;
import java.util.Set;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import cn.edu.zzuli.web.bean.rowmapper.UserRowMapper;

import com.google.inject.internal.Sets;

public class UserDetailsServiceImpl implements UserDetailsService {
	
	private JdbcTemplate jdbcTemplate;
	
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User result = null;
		
		String sql = "SELECT id, username, nickname, password, sex, birthday, major, address, introduces, enabled " +
				"FROM user WHERE username = ?";
		
		cn.edu.zzuli.web.bean.User user = (cn.edu.zzuli.web.bean.User) this.getJdbcTemplate().queryForObject(sql, 
				new Object[]{username}, new UserRowMapper());
		
		sql = "SELECT r.name FROM role r, user_role ur WHERE r.id = ur.rid AND ur.uid = ?";
		List<String> roles = this.getJdbcTemplate().queryForList(sql, new Object[]{user.getId()}, String.class);
		
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		for(int i = 0; i < roles.size(); i++){
			String role = roles.get(i);
			authSet.add(new SimpleGrantedAuthority(role));
		}
		
		result = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, true, true, true, authSet);
		
		return result;
	}
	
}
